%%%%This file finds the different threats along the Pareto-frontier of a
%%%%group of 2 that 2 players can make
%%%%You can calculate these once for each state

gamma2=[0.2:0.1:0.8]';
gamma2=[gamma2 [0.8:-0.1:0.2]'];
BLA=[];
for d=1:size(ewdev,1)
dperm=find(gamma2(d,1)==gamma2(:,2));
jodperm=find(S(j,1)==S(:,2) & S(j,2)==S(:,1) & S(j,3)==S(:,3));
   
if countgridod(d,j)>0
index=[1 j d];
%%starting guesses
BLA=[BLA; utility(rho,S(j,1))+beta*ewdev(d,statedev12(j),1) utility(rho,S(j,2))+beta*ewdev(d,statedev12(j),2)];
rr=find(utility(rho,cfirstbest(:,j,1))+beta*ewsb(:,j,1)<=utility(rho,S(j,1))+beta*ewdev(d,statedev12(j),1) & utility(rho,cfirstbest(:,j,2))+beta*ewsb(:,j,2)<=utility(rho,S(j,2))+beta*ewdev(d,statedev12(j),2));
if size(rr)>=1
x0=[c(rr(end),j,1) c(rr(end),j,2)];
x0=[x0 x0(2)/x0(1) (Y(j)-x0(2)-x0(1))/x0(1)];
[xsol, output] = agent12solverhog(x0,index,ewsb,waut);
xsol
output
outputkeep(d,j,1:3)=output(1:3);
xkeep(d,j,1:3)=[xsol(1:2) Y(j)-xsol(1)-xsol(2)];
if output(6)<=0 & d>1
x0=[xkeep(d-1,j,1) xkeep(d-1,j,2)];    
x0=[x0 x0(2)/x0(1) (Y(j)-x0(2)-x0(1))/x0(1)];
[xsol, output] = agent12solverhog(x0,index,ewsb,waut);
xsol
output
outputkeep(d,j,1:3)=output(1:3);
xkeep(d,j,1:3)=[xsol(1:2) Y(j)-xsol(1)-xsol(2)];   
end

if output(6)<=0
   error('did not converge') 
end

xkeepperm(dperm,jodperm,2)=xkeep(d,j,1);
xkeepperm(dperm,jodperm,1)=xkeep(d,j,2);
xkeepperm(dperm,jodperm,3)=xkeep(d,j,3);
outputkeepperm(dperm,jodperm,2)=outputkeep(d,j,1);
outputkeepperm(dperm,jodperm,1)=outputkeep(d,j,2);
outputkeepperm(dperm,jodperm,3)=outputkeep(d,j,3);
xkeep(dperm,jodperm,1:3)=xkeepperm(dperm,jodperm,1:3);
outputkeep(dperm,jodperm,1:3)=outputkeepperm(dperm,jodperm,1:3);
countgridod(d,j)=0;
countgridod(dperm,jodperm)=0;


end
end
end

if size(rr)>=1
jjperm=find(S(:,1)==S(j,1) & S(:,2)==S(j,3) & S(:,3)==S(j,2));
outputkeep13(:,jjperm,1)=outputkeep(:,j,1);
outputkeep13(:,jjperm,2)=outputkeep(:,j,3);
outputkeep13(:,jjperm,3)=outputkeep(:,j,2);

xkeep13(:,jjperm,1)=xkeep(:,j,1);
xkeep13(:,jjperm,2)=xkeep(:,j,3);
xkeep13(:,jjperm,3)=xkeep(:,j,2);

jjperm=find(S(:,1)==S(j,3) & S(:,2)==S(j,1) & S(:,3)==S(j,2));
outputkeep23(:,jjperm,1)=outputkeep(:,j,3);
outputkeep23(:,jjperm,2)=outputkeep(:,j,1);
outputkeep23(:,jjperm,3)=outputkeep(:,j,2);

xkeep23(:,jjperm,1)=xkeep(:,j,3);
xkeep23(:,jjperm,2)=xkeep(:,j,1);
xkeep23(:,jjperm,3)=xkeep(:,j,2);

jjperm=find(S(:,1)==S(j,3) & S(:,2)==S(j,2) & S(:,3)==S(j,1));
deviation23(:,jjperm,1)=outputkeep(:,j,3);
deviation23(:,jjperm,2)=outputkeep(:,j,2);
deviation23(:,jjperm,3)=outputkeep(:,j,1);

end


